//1.hash模式：早期的前端路由的实现就是基于location.hash来实现。原理：location.hash的值就是URL中#后面的内容

class BaseRouter {
  //list表示路由表
  constructor(list) {
    this.list = list;
  }
  //页面渲染函数
  render(state) {
    let ele = this.list.find(ele => ele.path === state);
    ele = ele ? ele : this.list.find(ele => ele.path === "*");
    ELEMENT.innerText = ele.component;
  }
}

class HashRouter extends BaseRouter {
  constructor(list) {
    super(list);
    this.handler();
    //监听hashchange事件
    window.addEventListener("hashchange", e => {
      this.handler();
    });
  }
  //hash改变时，重新渲染
  handler() {
    this.render(this.getState());
  }
  //获取hash值
  getState() {
    const hash = window.location.hash;
    return hash ? hash.slice(1) : "/";
  }
  //push 新的页面
  push(path) {
    window.location.hash = path;
  }
  //获取 默认页url
  getUrl(path) {
    const href = window.location.href;
    const i = href.indexOf("#");
    const base = i >= 0 ? href.slice(0, i) : href;
    return base + "#" + path;
  }
  //替换页面
  replace(path) {
    window.location.replace(this.getUrl(path));
  }
  go(n) {
    window.history.go(n);
  }
}

//2.history: HTML5提供了History API来实现URL的变化。主要的API有两个history.pushState()和historystore.replaceState()

class HistoryRouter extends BaseRouter {
  constructor(list) {
    super(list);
    this.handler();
    //监听popstate事件
    window.addEventListener("popstate", e => {
      this.handler;
    });
  }
  //渲染页面
  handler() {
    this.render(this.getState());
  }
  //获取url
  getState() {
    const path = window.location.pathname;
    return path ? path : "/";
  }
  push(path) {
    history.pushState(null, null, path);
    this.handler();
  }
  replace(path) {
    history.replaceState(null, null, path);
    this.handler();
  }
  go(n) {
    window.history.go(n);
  }
}
